from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView,CreateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import OrderingFilter
from goods.models import GoodsCategory, SKU
from goods.serializers import CategoriesListSerializer, SKUIndexSerializer, UserBrowseHistorySerializer, \
    OrderShowSerializer
from goods.utils import PageNum
from drf_haystack.viewsets import HaystackViewSet
from django_redis import get_redis_connection

from orders.models import OrderInfo


class CategoriesView(APIView):
    """
    面包屑导航
    """
    def get(self,request,id):
        cat3 = GoodsCategory.objects.get(id =id)
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            "cat1":cat1.name,
            "cat2":cat2.name,
            "cat3":cat3.name

        })


class CategoriesListView(ListAPIView):
    """
    详情页列表展示
    """
    serializer_class = CategoriesListSerializer
    pagination_class = PageNum
    filter_backends = [OrderingFilter]
    ordering_fields = ("create_time","sales","price")
    def get_queryset(self):
        pk = self.kwargs["pk"]
        return  SKU.objects.filter(category_id=pk)

class  SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索功能实现
    """
    # 使用SKU 模型类进行返回
    index_models = [SKU]
    pagination_class = PageNum
    serializer_class = SKUIndexSerializer


class UserBrowseHistoryView(CreateAPIView):
    """
    浏览历史记录保存 和展示
    """
    serializer_class = UserBrowseHistorySerializer

    def get(self, request):
        # 1.通过请求头部信息获取用户信息
        user = request.user
        # 2.连接redis 数据库
        coon = get_redis_connection("history")
        # 通过用户查询sku_id
        sku_ids = coon.lrange("history_%s",0,5)
        # 通过sku_id 查询商品信息
        sku = SKU.objects.filter(id__in =sku_ids)
        # 序列化返回商品信息
        ser = CategoriesListSerializer(sku,many=True)
        return Response(ser.data)


class OrderShowView(ListAPIView):
    """ 用户订单列表展示 """
    serializer_class = OrderShowSerializer
    # 仅通过认证的用户
    permission_classes = [IsAuthenticated]
    # 分页属性
    pagination_class = PageNum
    filter_backends = [OrderingFilter]
    ordering_fields = ('order_id', )

    def get_queryset(self):
        # 获取
        user = self.request.user

        try:
            # 查询
            queryset = OrderInfo.objects.filter(user_id=user.id)
        except:
            return Response({'error': '查询失败'})
        else:
            # 返回
            return queryset